package cn.dglydrpy.fundmanagement.service.impl;

import cn.dglydrpy.fundmanagement.dao.entiey.InvestmentGoal;
import cn.dglydrpy.fundmanagement.dao.mapper.InvestmentGoalMapper;
import cn.dglydrpy.fundmanagement.service.IInvestmentGoalService;
import cn.dglydrpy.fundmanagement.service.IPortfolioService;
import cn.dglydrpy.fundmanagement.service.dto.InvestmentGoalDto;
import cn.dglydrpy.fundmanagement.service.dto.PortfolioDto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class InvestmentGoalService implements IInvestmentGoalService {

    @Autowired
    private InvestmentGoalMapper investmentGoalMapper;

    @Autowired
    private IPortfolioService portfolioService;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public int saveInvestmentGoal(InvestmentGoalDto investmentGoalDto) {
        InvestmentGoal investmentGoal = new InvestmentGoal();
        BeanUtils.copyProperties(investmentGoalDto, investmentGoal);
        investmentGoal.setCreatedTime(sdf.format(new Date()));
        investmentGoal.setUpdatedTime(sdf.format(new Date()));
        if (investmentGoal.getStatus() == null || investmentGoal.getStatus().isEmpty()) {
            investmentGoal.setStatus("1"); // 1-有效 0-无效
        }
        if (investmentGoal.getAchieved() == null || investmentGoal.getAchieved().isEmpty()) {
            investmentGoal.setAchieved("0"); // 0-未达成 1-已达成
        }
        return investmentGoalMapper.insert(investmentGoal);
    }

    @Override
    public void updateInvestmentGoal(InvestmentGoalDto investmentGoalDto) {
        InvestmentGoal investmentGoal = new InvestmentGoal();
        BeanUtils.copyProperties(investmentGoalDto, investmentGoal);
        investmentGoal.setUpdatedTime(sdf.format(new Date()));
        investmentGoalMapper.updateById(investmentGoal);
    }

    @Override
    public void deleteInvestmentGoal(Long id) {
        investmentGoalMapper.deleteById(id);
    }

    @Override
    public InvestmentGoalDto getInvestmentGoalById(Long id) {
        InvestmentGoal investmentGoal = investmentGoalMapper.selectById(id);
        if (investmentGoal == null) {
            return null;
        }
        InvestmentGoalDto investmentGoalDto = new InvestmentGoalDto();
        BeanUtils.copyProperties(investmentGoal, investmentGoalDto);
        setGoalTypeName(investmentGoalDto);
        setAchievedName(investmentGoalDto);
        
        // 获取投资组合的收益率作为当前值
        if (investmentGoalDto.getPortfolioId() != null) {
            PortfolioDto portfolio = portfolioService.getPortfolioById(investmentGoalDto.getPortfolioId());
            if (portfolio != null && portfolio.getTotalProfitRate() != null) {
                investmentGoalDto.setCurrentValue(portfolio.getTotalProfitRate());
                // 判断是否达成目标
                checkIfGoalAchieved(investmentGoalDto);
            }
        }
        
        return investmentGoalDto;
    }

    @Override
    public Page<InvestmentGoalDto> getInvestmentGoalsByConditions(String portfolioId, String goalType, String achieved, int pageNo, int pageSize) {
        Page<InvestmentGoal> page = new Page<>(pageNo, pageSize);
        QueryWrapper<InvestmentGoal> queryWrapper = new QueryWrapper<>();
        if (portfolioId != null && !portfolioId.isEmpty()) {
            queryWrapper.eq("portfolio_id", portfolioId);
        }
        if (goalType != null && !goalType.isEmpty()) {
            queryWrapper.eq("goal_type", goalType);
        }
        if (achieved != null && !achieved.isEmpty()) {
            queryWrapper.eq("achieved", achieved);
        }
        queryWrapper.eq("status", "1");
        queryWrapper.orderByDesc("created_time");
        investmentGoalMapper.selectPage(page, queryWrapper);

        Page<InvestmentGoalDto> dtoPage = new Page<>(pageNo, pageSize, page.getTotal());
        List<InvestmentGoalDto> records = page.getRecords().stream().map(investmentGoal -> {
            InvestmentGoalDto dto = new InvestmentGoalDto();
            BeanUtils.copyProperties(investmentGoal, dto);
            setGoalTypeName(dto);
            setAchievedName(dto);
            
            // 获取投资组合的收益率作为当前值
            if (dto.getPortfolioId() != null) {
                PortfolioDto portfolio = portfolioService.getPortfolioById(dto.getPortfolioId());
                if (portfolio != null && portfolio.getTotalProfitRate() != null) {
                    dto.setCurrentValue(portfolio.getTotalProfitRate());
                    // 判断是否达成目标
                    checkIfGoalAchieved(dto);
                }
            }
            
            return dto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(records);
        return dtoPage;
    }

    @Override
    public List<InvestmentGoalDto> getAllInvestmentGoals() {
        QueryWrapper<InvestmentGoal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        queryWrapper.orderByDesc("created_time");
        List<InvestmentGoal> investmentGoals = investmentGoalMapper.selectList(queryWrapper);
        return investmentGoals.stream().map(investmentGoal -> {
            InvestmentGoalDto dto = new InvestmentGoalDto();
            BeanUtils.copyProperties(investmentGoal, dto);
            setGoalTypeName(dto);
            setAchievedName(dto);
            
            // 获取投资组合的收益率作为当前值
            if (dto.getPortfolioId() != null) {
                PortfolioDto portfolio = portfolioService.getPortfolioById(dto.getPortfolioId());
                if (portfolio != null && portfolio.getTotalProfitRate() != null) {
                    dto.setCurrentValue(portfolio.getTotalProfitRate());
                    // 判断是否达成目标
                    checkIfGoalAchieved(dto);
                }
            }
            
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public void checkAndSendReminders() {
        // 检查目标是否达成并发送提醒
        List<InvestmentGoalDto> allGoals = getAllInvestmentGoals();
        for (InvestmentGoalDto goal : allGoals) {
            // 更新投资组合的当前收益率
            if (goal.getPortfolioId() != null) {
                PortfolioDto portfolio = portfolioService.getPortfolioById(goal.getPortfolioId());
                if (portfolio != null && portfolio.getTotalProfitRate() != null) {
                    goal.setCurrentValue(portfolio.getTotalProfitRate());
                    // 判断是否达成目标
                    checkIfGoalAchieved(goal);
                    
                    // 更新数据库中的当前值和达成状态
                    InvestmentGoal investmentGoal = new InvestmentGoal();
                    BeanUtils.copyProperties(goal, investmentGoal);
                    investmentGoal.setUpdatedTime(sdf.format(new Date()));
                    investmentGoalMapper.updateById(investmentGoal);
                }
            }
        }
    }

    /**
     * 检查目标是否达成
     * @param dto 投资目标DTO
     */
    private void checkIfGoalAchieved(InvestmentGoalDto dto) {
        if (dto.getCurrentValue() != null && dto.getTargetValue() != null) {
            // 对于收益目标，当收益率大于等于目标值时达成
            if (dto.getCurrentValue().compareTo(dto.getTargetValue()) >= 0) {
                dto.setAchieved("1"); // 已达成
                setAchievedName(dto);
            }
        }
    }

    private void setGoalTypeName(InvestmentGoalDto dto) {
        if ("1".equals(dto.getGoalType())) {
            dto.setGoalTypeName("收益目标");
        } else if ("2".equals(dto.getGoalType())) {
            dto.setGoalTypeName("价格提醒");
        }
    }

    private void setAchievedName(InvestmentGoalDto dto) {
        if ("0".equals(dto.getAchieved())) {
            dto.setAchievedName("未达成");
        } else if ("1".equals(dto.getAchieved())) {
            dto.setAchievedName("已达成");
        }
    }
}